﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Runtime.InteropServices;

namespace OT.Common
{
    /// <summary>
    /// 封装Session，此类内部不能定义任何类级变量。
    /// </summary>
    public class SessionCache
    {
        #region 常量
        public const string UserID = "UserID";
        public const string LoginUser = "LoginUser";
        #endregion

        private static SessionCache mSessionCache = new SessionCache();
        public static SessionCache Session
        {
            get { return mSessionCache; }
        }

        private readonly int mCacheSize = 1024 * 100;

        private bool AddData(string pKey,object pobj)
        {
            if (!CheckDataSize(pobj))
                return false;
            if (pKey.Trim().Length == 0)
                return false;
            try
            {
                HttpContext.Current.Session[pKey] = pobj;
            }
            catch
            {
                return false;
            }
            return true;
        }

        public bool RemoveData(string pKey)
        {
            if (pKey.Trim().Length == 0)
                return false;

            try
            {
                HttpContext.Current.Session.Remove(pKey);
            }
            catch
            {
                return false;
            }
            return true;
        }

        public bool Clear()
        {
            try
            {
                HttpContext.Current.Session.Clear();
            }
            catch
            {
                return false;
            }
            return true;
        }

        public int CacheCountSize()
        {
            int _CacheCountSize = 0;
            try
            {
                foreach (object var in HttpContext.Current.Session)
                {
                    _CacheCountSize += BinarySeries.SeriesObjectSize(var);
                }
            }
            catch
            {
                _CacheCountSize = 0;
            }
            return _CacheCountSize;
        }

        public object this[string pstr]
        {
            get 
            {
                object _obj = HttpContext.Current.Session[pstr];
                return _obj;
            }

            set
            {
                AddData(pstr, value);
            }
        }

        private bool CheckDataSize(object pobj)
        {
            if (pobj == null)
                return false;
            int _ObjectSize = BinarySeries.SeriesObjectSize(pobj);
            if (_ObjectSize > mCacheSize)
                return false;
            return true;
        }
    }
}
